import { DefaultBaseUrl, DefaultHeaders } from '@/constants'
import { useAuthStore } from '@/store'
import un from '@uni-helper/uni-network'
import qs from 'qs'
import { showNetworkError } from './helper'
import { sm4 } from "sm-crypto";
// 引入SM2模块
// import { sm4 } from 'miniprogram-sm-crypto';


const SMconfig = {
  enabled: true,
  SMKey: "B86F0E70E2983D4FDF8D61519C276B3E"
}
// const DECRYPT = false
// const SMKey = "B86F0E70E2983D4FDF8D61519C276B3E";
// 加密函数
const encrypt = (data: any) => {
  try {
    // if (!SMconfig.enabled) return data;

    if (typeof data !== "string") {
      data = JSON.stringify(data);
    }
    return sm4.encrypt(data, SMconfig.SMKey);
  } catch (e) {
    console.log(e);
  }
};
const decrypt = (encryptedData: any) => {
  try {
    // if (!SMconfig.enabled) return encryptedData;
    const decrypted = sm4.decrypt(encryptedData, SMconfig.SMKey);
    try {
      return JSON.parse(decrypted);
    } catch {
      return decrypted;
    }

  } catch (e) {
    console.log(e);
  }
};

const instance = un.create({
  baseUrl: DefaultBaseUrl,
  timeout: 30_000,
  paramsSerializer: (params: any) => {
    const query = qs.stringify(
      Object.fromEntries(
        Object.entries(params).filter(
          ([, v]) => !['undefined', 'null', undefined, null].includes((v as any)?.toString() ?? v),
        ),
      ),
    )

    return query
  },
})

instance.interceptors.request.use((config) => {
  const authStore = useAuthStore()
  config.headers = {
    ...DefaultHeaders,
    // 'token': authStore.token,
    // 'X-Token': authStore.token,
    'X-Authorization': authStore.token,
    NeadDecrypt: SMconfig.enabled ? 'Y' : 'N',
    ...config.headers,
  }
  console.log('Request')
  console.log(config.url)
  console.log(config.data)
  const data = config.data
  config.data = SMconfig.enabled ? { mark: encrypt(data || {}) } : data;
  return config
})
instance.interceptors.response.use((res) => {
  const response = res as IUnResponse

  const data = response.data;
  if (SMconfig.enabled) {
    response.data = decrypt(data?.mark);
  }
  console.log('Response')
  console.log(response)

  if (response.data?.status === 'error' || response.data?.status === 'fail') {
    showNetworkError({
      response: response as IUnResponse,
      error: response as IUnError,
      type: response.config?.showErrorType,
    })
  } else if (response.data?.status === 'expire' || response.data?.status === 'tokenExpire') {
    // showNetworkError({
    //   response: response as IUnResponse,
    //   error: response as IUnError,
    //   type: response.config?.showErrorType,
    // })
    const pages = getCurrentPages()
    const page: any = pages[pages.length - 1]
    if (!/login\/index/.test(page.route)) {
      // 不在登录页，跳到登录页
      uni.redirectTo({
        url: '/pages/login/index'
      })
    }
  }
  return response
})

export { instance as unInstance }
